/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.rpc

import com.google.gson.Gson
import cool.taomu.software.fig.objectpool.ObjectPoolFactory
import cool.taomu.software.fig.rpc.entity.RpcEntity
import cool.taomu.software.fig.rpc.entity.RpcResultEntity
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.util.List
import java.util.Vector
import org.slf4j.LoggerFactory
import io.netty.channel.ChannelHandler.Sharable

@Sharable
class RpcServerHandler extends ChannelInboundHandlerAdapter {
    val LOG = LoggerFactory.getLogger(RpcServerHandler);

    override channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        var gson = new Gson();
        var rpcEntity = gson.fromJson(msg as String, RpcEntity);
        //添加解密方法
        LOG.debug(rpcEntity.toString());
        var mtype = MethodType.methodType(rpcEntity.returnType, rpcEntity.parameterTypes);
        var mhandle = MethodHandles.lookup.findVirtual(rpcEntity.inter, rpcEntity.methodName, mtype)
        var resutls = new RpcResultEntity();
        if (rpcEntity.parameterTypes.size > 0) {
            try(var opool = ObjectPoolFactory.borrowObject(rpcEntity.inter)) {
                var List<Object> a = new Vector<Object>();
                a.add(opool.instance);
                a.addAll(rpcEntity.arguments);
                var res = mhandle.invokeWithArguments(a);
                resutls.result = res;
            }
        } else {
            try(var opool = ObjectPoolFactory.borrowObject(rpcEntity.inter)) {
                var List<Object> a = new Vector<Object>();
                a.add(opool.instance);
                var res = mhandle.invokeWithArguments(a);
                resutls.result = res;
            }
        }
        ctx.writeAndFlush = gson.toJson(resutls);
        ctx.close();
    }

    override channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    override exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
